package com.cunshe.service;

import com.cunshe.common.DictConsts;
import com.cunshe.dao.NewsDao;
import com.cunshe.domain.News;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sunkee.entity.page.Pageable;
import com.sunkee.entity.page.Pageination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 新闻资讯
 * @author xiao
 */
@Service
public class NewsService {

    @Autowired
    private NewsDao newsDao;

    /** 新增 */
    @Transactional(rollbackFor = Exception.class)
    public int insert(News record) {
        record.setCreatetime(new Date());
        return newsDao.insert(record);
    }

    /** 删除 */
    @Transactional(rollbackFor = Exception.class)
    public int delete(Long id) {
        return newsDao.delete(id);
    }

    /** 修改 */
    @Transactional(rollbackFor = Exception.class)
    public int update(News record) {
        record.setUpdatetime(new Date());
        return newsDao.update(record);
    }

    /** 查询 */
    public News get(long id) {
        return list(News.builder().id(id).build())
                .stream()
                .findFirst()
                .orElse(null);
    }

    /** 查询列表 */
    public List<News> top(int top, int type) {
        PageHelper.startPage(0, top, " home_recommend DESC ");
        return list(News.builder().type(type).build());
    }

    /** 查询列表 */
    public Pageable<News> pagelist(int pageNo, int pageSize, News record) {
        Page<List<News>> page = PageHelper.startPage(pageNo, pageSize, " id DESC ");
        List<News> list = newsDao.list(record);
        Pageination<News> of = Pageination.of(pageNo, pageSize);
        of.setResult(list);
        of.setCount(page.getTotal());
        return of;
    }

    /** 查询列表 */
    public List<News> list(News record) {
        return newsDao.list(record);
    }

}